<?php

namespace app\api\controller\baiying;


use app\common\exception\UploadException;
use EasyWeChat\Kernel\Exceptions\Exception;
use think\Config;
use think\Hook;
use baiying\lib\BYTokenClient;
use think\Db;

/**
 * 公共接口
 */
class Bybidui extends Bybase {

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';

    public function _initialize() {
        parent::_initialize();
    }



    public function autoBatchTaskLoudiaoList(){
        $end_list = [];

        $request_data = $this->request->param();

        if(!empty($request_data['jobid'])){
            $calljobid = explode(',',$request_data['jobid']);
        }
        $resultQueryList_ = [
            ['name'=>'客户意向等级','value'=>'B'],
        ];
        $resultQueryList = json_encode($resultQueryList_,JSON_UNESCAPED_UNICODE);
        $save_data = array();
        foreach ($calljobid as $val) {
            $exist_instanceid_list = db(getBaiYingDataTable())->where([
                'yixiang_value'=>['in',['A','B']],
                'callJobId'=>$val,
                'createtime'=>['>',strtotime('today')],
            ])->column('callInstanceId');
            $pageNum = 1;

            $pageTotal = 99999;

//            date("Y-m-d")
            $starttime = date("Y-m-d") . ' 00:00:00';
//            $starttime = '2025-07-30 00:00:00';

            while (true){
                if($pageNum > $pageTotal) break;
                $item_request_data = array('startTime'=>$starttime,'callJobId'=>$val,'pageNum'=>$pageNum,'pageSize'=>300,'resultQueryList'=>$resultQueryList);
                $item_response = $this->getAiTaskDetai1($item_request_data,$this->access_token,$this->companyId);
                try{

                    if($item_response['data']['total'] == count($exist_instanceid_list)) {
                        break;
                    }else{
                        if($pageTotal == 99999){
                            $pageTotal = $item_response['data']['pages'];
                        }

                    }
                }catch (\Exception $e){
                    var_dump($pageNum,$pageTotal,$item_request_data);
                    var_dump($item_response);exit;
                }



                $tmp_data = [];
                foreach ($item_response['data']['list'] as $item) {
                    if(!in_array($item['callInstanceId'],$exist_instanceid_list)){
                        $tmp_data[] = self::taskPhoneInsert($item);
                    }

                }


                $save_data = array_merge($save_data,$tmp_data);
                $pageNum = $pageNum + 1;
            }



            

        }
        db(getBaiYingDataTable())->insertAll($save_data);

        $this->success('',[count($save_data)]);
    }















    public static function getAiTaskDetai1($request_data,$access_token,$companyId) {

        $client = new BYTokenClient($access_token);

        $method = 'byai.openapi.calljob.calldone.list'; //要调用的api名称
        $api_version = '1.0.0'; //要调用的api版本号


        $my_params = ['companyId' => $companyId];
        $my_params = array_merge($my_params,$request_data);
        $my_files = [];

        $result = $client->post($method, $api_version, $my_params, $my_files);
        qqq('getAiTaskDetai1',$result);

        return $result;

    }





    public static function taskPhoneInsert($data){
        if(empty($data)) return false;

        $save_data = [];
        $is_exist = db(getBaiYingDataTable())->where('callInstanceId',$data['callInstanceId'])->count();
        if(!empty($is_exist)) return false;
        $save_data = [
            'origin'=>1,
            'is_yixiang'=>0,
            'callInstanceId'=>$data['callInstanceId'],
            'callJobId'=>$data['callJobId'],
            'customerTelephone'=>$data['customerTelephone'],
            'customerName'=>$data['customerName'],
            'startTime'=>$data['startTime'],
            'endTime'=>$data['endTime'],
            'duration'=>$data['duration'],
            'luyinOssUrl'=>$data['luyinOssUrl'],
        ];


        $resultList = $data['resultList'];
        if(!empty($resultList[0]['name']) && $resultList[0]['name'] == '客户意向等级'){
            preg_match('/[a-zA-Z]/', $resultList[0]['value'], $matches);
            $save_data['is_yixiang'] = 1;
            $save_data['yixiang_txt'] = $resultList[0]['value'];
            $save_data['yixiang_value'] = !empty($matches[0])?$matches[0]:'';
        }else{
            $save_data['is_yixiang'] = 0;
        }



        $save_data['config'] = json_encode($save_data,JSON_UNESCAPED_UNICODE);
        $save_data['createtime'] = time();

        if(empty($save_data)) return false;
        return $save_data;






    }








}
